<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Kafka WebSocket Visualization (Cumulative with Charts)</title>
  <script src="https://cdn.socket.io/4.6.1/socket.io.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
  <style>
    body { font-family: Arial, sans-serif; margin: 20px; }
    .container { display: flex; flex-wrap: wrap; gap: 20px; }
    .chart-container { width: 48%; height: 400px; }
  </style>
</head>
<body>
  <h1>Kafka WebSocket Visualization (Cumulative)</h1>
  <div class="container">
<!-- 图表 4: 各个班级的男女的人数 (饼状图) -->
    <div class="chart-container" id="class-gender-pie-chart"></div>
  </div>
<script>
    const socket = io('http://localhost:5000');

    // 全局累计数据
    const cumulativeData = {
      classGender: {}, // { class: { male: count, female: count } }
    };

    // 初始化 ECharts 图表实例
    const classGenderPieChart = echarts.init(document.getElementById('class-gender-pie-chart'));

    // 图表配置

    const classGenderPieChartOption = {
      title: { text: '各个班级的男女人数 (累计)', left: 'center' },
      tooltip: { trigger: 'item' },
      legend: { bottom: '0' },
      series: [
        {
          name: '人数',
          type: 'pie',
          radius: '50%',
          data: []
        }
      ]
    };
    classGenderPieChart.setOption(classGenderPieChartOption);

    // 累计数据处理函数
    socket.on('kafka-message', (message) => {
      const parsedMessage = JSON.parse(message.data);
      const introduction = parsedMessage.introduction;
      const result = parsedMessage.result;

      if (introduction.includes('统计各个班级的男女的人数')) {
        const entries = result.split(';').map(entry => {
          const match = entry.match(/Class: ([^,]+), Gender: ([^,]+), Count: (\d+)/);
          if (match) {
            const className = match[1];
            const gender = match[2];
            const count = parseInt(match[3], 10);

            if (!cumulativeData.classGender[className]) {
              cumulativeData.classGender[className] = { male: 0, female: 0 };
            }
            cumulativeData.classGender[className][gender] += count;
          }
        });

        const pieData = Object.entries(cumulativeData.classGender)
          .flatMap(([className, counts]) => [
            { name: `${className} (男)`, value: counts.male },
            { name: `${className} (女)`, value: counts.female }
          ]);
        classGenderPieChartOption.series[0].data = pieData;
        classGenderPieChart.setOption(classGenderPieChartOption);
      }
    });
</script>
</body>
</html>